package reflect;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author Jun jie Yi
 * 2022/5/24 22:38
 */
public class CjlibDemo {
    public static void main(String[] args) {
        Enhancer en = new Enhancer();//用来帮我们生成代理对象
        en.setSuperclass(ZStar.class);//设置要代理的目标类
        en.setCallback(new TargetCglib(new ZStar()));//设置执行规则，相当于proxy的Ruler
        ZStar s = (ZStar) en.create();//创造代理对象
        s.dance();//方法测试
        System.out.println("********************");
        s.sing();
    }
}

class TargetCglib implements MethodInterceptor {
    private ZStar zStar;
    public TargetCglib(ZStar zStar) {
        this.zStar = zStar;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("签合同");
        Object invoke = methodProxy.invokeSuper(o, objects);//调用原方法
        //Object invoke = method.invoke(zStar, objects);
        //Object invoke = methodProxy.invokeSuper(zStar, objects);
        System.out.println("收钱");
        return invoke;
    }
}

class ZStar {

    public void sing() {
        System.out.println("我会唱歌.......");
    }

    public void dance() {
        System.out.println("我会跳舞......");
    }
}